package controllers.games;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.swing.JButton;
import javax.swing.SwingWorker;

import models.games.MemorizzaTabella;
import models.util.Indexes;
import views.games.MemorizzaTabellaView;
import core.GameLauncher;
import core.GameLauncher.State;
import core.constants.Constants;

public class MemorizzaTabellaController implements ActionListener {

	private MemorizzaTabellaView view;
	private MemorizzaTabella model;
	private Indexes[] trueTiles;
	private List<Indexes> alreadyFound = new ArrayList<Indexes>();
	private int round = 1;
	private final int MAX_ROUNDS = Constants.getRounds();
	private GameLauncher gameLauncher;

	public MemorizzaTabellaController(MemorizzaTabella model,
			MemorizzaTabellaView view, GameLauncher gameLauncher) {
		this.view = view;
		this.model = model;
		this.gameLauncher = gameLauncher;
		trueTiles = model.getTrueTiles();
		view.addActionListenerToTheCells(new CellActionListener(gameLauncher));
		view.setTiles(trueTiles.length);
		showTrueTiles(false);
	}

	private void newRound(boolean won) {
		model.refresh(won);
		if (round == MAX_ROUNDS) {
			view.setScore(model.getScore());
			view.gameEnded();
			return;
		}
		view.setScore(model.getScore());
		round++;
		view.setRounds(round);
		trueTiles = model.getTrueTiles();
		alreadyFound.clear();
		view.update(model.getDimension());// dimensione massima sarà 8x8
		view.setTiles(trueTiles.length);
		view.addActionListenerToTheCells(new CellActionListener(gameLauncher));
		showTrueTiles(false);
	}

	private class CellActionListener implements ActionListener {

		private GameLauncher gameLauncher;

		public CellActionListener(GameLauncher gameLauncher) {
			super();
			this.gameLauncher = gameLauncher;
		}

		@Override
		public void actionPerformed(ActionEvent a) {
			JButton cell = (JButton) a.getSource();

			String inputText = cell.getText();
			if (inputText.equals("Ricomincia")) {
				MemorizzaTabella newModel = new MemorizzaTabella(
						model.getCurrentUser());
				MemorizzaTabellaView newView = new MemorizzaTabellaView(2);
				MemorizzaTabellaController newController = new MemorizzaTabellaController(
						newModel, newView, gameLauncher);
				gameLauncher.setGame(newModel, newView, newController);
				gameLauncher.startTransition(State.GAME);
				model.addGameToDatabase();
				System.out.println("Ricomincia");
			} else if (inputText.equals("Menu Giochi")) {
				gameLauncher.startTransition(State.GAME_MENU);
				model.addGameToDatabase();
				System.out.println("Menu Giochi");
			} else {
				int i = Integer.parseInt("" + cell.getName().charAt(0));
				int j = Integer.parseInt("" + cell.getName().charAt(2));
				if (model.verify(i, j)) {
					Indexes ind = new Indexes(i, j);
					if (alreadyFound.contains(ind))
						return;
					cell.setBackground(Color.ORANGE);
					alreadyFound.add(ind);
					if (trueTiles.length == alreadyFound.size()) {
						newRound(true);
					}
					gameLauncher.correctAnswer();
				} else {
					cell.setBackground(Color.RED);
					showTrueTiles(true);
				}
			}
		}

	}

	private void showTrueTiles(boolean error) {
		JButton[][] cells = view.getCells();
		disableAll(cells);
		for (int k = 0; k < trueTiles.length; k++) {
			int i = trueTiles[k].getI();
			int j = trueTiles[k].getJ();
			cells[i][j].setBackground(Color.orange);
		}
		hideTrueTilesWorker htw = new hideTrueTilesWorker(cells, error);
		htw.execute();
	}

	private void disableAll(JButton[][] cells) {
		for (int i = 0; i < cells.length; i++)
			for (int j = 0; j < cells[0].length; j++)
				cells[i][j].setEnabled(false);
	}

	class hideTrueTilesWorker extends SwingWorker<Void, Void> {

		private JButton[][] cells;
		private boolean error;

		public hideTrueTilesWorker(JButton[][] cells, boolean error) {
			this.cells = cells;
			this.error = error;
		}

		@Override
		protected Void doInBackground() throws Exception {
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}

		public void done() {
			for (int k = 0; k < trueTiles.length; k++) {
				int i = trueTiles[k].getI();
				int j = trueTiles[k].getJ();
				cells[i][j].setBackground(Color.white);
			}
			enableAll(cells);
			if (error)
				newRound(false);
		}

		private void enableAll(JButton[][] cells) {
			for (int i = 0; i < cells.length; i++)
				for (int j = 0; j < cells[0].length; j++)
					cells[i][j].setEnabled(true);
		}

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub

	}

}
